import os
import textwrap

def replace_files(base_dir):
    # 1. 更新对话框布局文件 (添加测试按钮)
    dialog_layout = """
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- 时间选择 - 直接编辑 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:paddingBottom="8dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="时间:"
                android:textSize="16sp"/>

            <EditText
                android:id="@+id/et_hour"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:inputType="number"
                android:maxLength="2"
                android:hint="时"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=":"
                android:textSize="16sp"
                android:layout_marginHorizontal="4dp"/>

            <EditText
                android:id="@+id/et_minute"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:maxLength="2"
                android:hint="分"/>
        </LinearLayout>

        <!-- TTS文本输入 -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提醒文本:"
            android:textSize="16sp"
            android:paddingBottom="4dp"/>

        <EditText
            android:id="@+id/et_tts"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="输入语音播报内容"
            android:inputType="textCapSentences"
            android:maxLines="3"/>

        <!-- 重复设置 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:paddingTop="16dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="重复:"
                android:textSize="16sp"/>

            <RadioGroup
                android:id="@+id/rg_repeat"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:orientation="horizontal">

                <RadioButton
                    android:id="@+id/rb_once"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="仅一次"/>

                <RadioButton
                    android:id="@+id/rb_repeat"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:text="每周重复"/>
            </RadioGroup>
        </LinearLayout>

        <!-- 星期选择 -->
        <LinearLayout
            android:id="@+id/week_days_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="16dp">

            <CheckBox
                android:id="@+id/cb_sun"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="日"/>

            <CheckBox
                android:id="@+id/cb_mon"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="一"/>

            <CheckBox
                android:id="@+id/cb_tue"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="二"/>

            <CheckBox
                android:id="@+id/cb_wed"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="三"/>

            <CheckBox
                android:id="@+id/cb_thu"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="四"/>

            <CheckBox
                android:id="@+id/cb_fri"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="五"/>

            <CheckBox
                android:id="@+id/cb_sat"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="六"/>
        </LinearLayout>

        <!-- 测试按钮 -->
        <Button
            android:id="@+id/btn_test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:text="测试闹钟"
            android:backgroundTint="#2196F3"
            android:textColor="@android:color/white"/>

        <!-- 按钮区域 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="end"
            android:paddingTop="24dp">

            <Button
                android:id="@+id/btn_cancel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="取消"/>

            <Button
                android:id="@+id/btn_save"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:text="保存"/>
        </LinearLayout>
    </LinearLayout>
</ScrollView>
"""

    # 2. 更新MainActivity.java (修复保存问题，添加测试功能)
    main_activity = """
package com.example.voicealarm;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private ListView alarmListView;
    private FloatingActionButton fabAdd;
    private AlarmAdapter adapter;
    private ArrayList<Alarm> alarms = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        alarmListView = findViewById(R.id.alarm_list);
        fabAdd = findViewById(R.id.fab_add);
        
        loadAlarms();
        setupListView();
        setupAddButton();
    }

    private void loadAlarms() {
        // 示例数据
        Alarm alarm1 = new Alarm();
        alarm1.id = 1;
        alarm1.time = Calendar.getInstance();
        alarm1.time.set(Calendar.HOUR_OF_DAY, 8);
        alarm1.time.set(Calendar.MINUTE, 0);
        alarm1.activeDays = new boolean[]{false, true, true, true, true, true, false};
        alarm1.ttsText = "早上好，该起床了";
        
        Alarm alarm2 = new Alarm();
        alarm2.id = 2;
        alarm2.time = Calendar.getInstance();
        alarm2.time.set(Calendar.HOUR_OF_DAY, 22);
        alarm2.time.set(Calendar.MINUTE, 30);
        alarm2.activeDays = new boolean[]{true, true, true, true, true, true, true};
        alarm2.ttsText = "该睡觉了，晚安";
        
        alarms.add(alarm1);
        alarms.add(alarm2);
        
        Collections.sort(alarms, (a1, a2) -> a1.time.compareTo(a2.time));
    }

    private void setupListView() {
        adapter = new AlarmAdapter(this, alarms);
        alarmListView.setAdapter(adapter);
        
        alarmListView.setOnItemClickListener((parent, view, position, id) -> {
            Alarm alarm = alarms.get(position);
            showEditAlarmDialog(alarm);
        });
    }

    private void setupAddButton() {
        fabAdd.setOnClickListener(view -> {
            Alarm newAlarm = new Alarm();
            newAlarm.time = Calendar.getInstance();
            newAlarm.ttsText = "该起床了";
            showEditAlarmDialog(newAlarm);
        });
    }
    
    private void showEditAlarmDialog(Alarm alarm) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_alarm, null);
        builder.setView(dialogView);
        
        // 初始化视图
        EditText etHour = dialogView.findViewById(R.id.et_hour);
        EditText etMinute = dialogView.findViewById(R.id.et_minute);
        EditText etTts = dialogView.findViewById(R.id.et_tts);
        RadioGroup rgRepeat = dialogView.findViewById(R.id.rg_repeat);
        LinearLayout weekDaysContainer = dialogView.findViewById(R.id.week_days_container);
        CheckBox[] dayCheckBoxes = new CheckBox[]{
            dialogView.findViewById(R.id.cb_sun),
            dialogView.findViewById(R.id.cb_mon),
            dialogView.findViewById(R.id.cb_tue),
            dialogView.findViewById(R.id.cb_wed),
            dialogView.findViewById(R.id.cb_thu),
            dialogView.findViewById(R.id.cb_fri),
            dialogView.findViewById(R.id.cb_sat)
        };
        Button btnTest = dialogView.findViewById(R.id.btn_test);
        
        // 设置初始值
        etHour.setText(String.format(Locale.getDefault(), "%02d", alarm.time.get(Calendar.HOUR_OF_DAY)));
        etMinute.setText(String.format(Locale.getDefault(), "%02d", alarm.time.get(Calendar.MINUTE)));
        etTts.setText(alarm.ttsText);
        
        // 设置重复模式
        boolean isRepeating = false;
        for (boolean day : alarm.activeDays) {
            if (day) {
                isRepeating = true;
                break;
            }
        }
        
        if (isRepeating) {
            rgRepeat.check(R.id.rb_repeat);
            weekDaysContainer.setVisibility(View.VISIBLE);
            for (int i = 0; i < dayCheckBoxes.length; i++) {
                dayCheckBoxes[i].setChecked(alarm.activeDays[i]);
            }
        } else {
            rgRepeat.check(R.id.rb_once);
            weekDaysContainer.setVisibility(View.GONE);
        }
        
        // 时间输入验证
        etHour.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    int hour = Integer.parseInt(s.toString());
                    if (hour > 23) {
                        etHour.setText("23");
                        etHour.setSelection(2);
                    }
                }
            }
            
            @Override
            public void afterTextChanged(Editable s) {}
        });
        
        etMinute.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    int minute = Integer.parseInt(s.toString());
                    if (minute > 59) {
                        etMinute.setText("59");
                        etMinute.setSelection(2);
                    }
                }
            }
            
            @Override
            public void afterTextChanged(Editable s) {}
        });
        
        // 重复模式切换
        rgRepeat.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_repeat) {
                weekDaysContainer.setVisibility(View.VISIBLE);
            } else {
                weekDaysContainer.setVisibility(View.GONE);
            }
        });
        
        AlertDialog dialog = builder.create();
        
        // 测试按钮
        btnTest.setOnClickListener(v -> {
            // 更新闹钟时间为当前时间+10秒用于测试
            Calendar testTime = Calendar.getInstance();
            testTime.add(Calendar.SECOND, 10);
            
            Alarm testAlarm = new Alarm();
            testAlarm.id = System.currentTimeMillis();
            testAlarm.time = testTime;
            testAlarm.ttsText = etTts.getText().toString();
            
            // 设置星期
            boolean isRepeat = rgRepeat.getCheckedRadioButtonId() == R.id.rb_repeat;
            if (isRepeat) {
                for (int i = 0; i < dayCheckBoxes.length; i++) {
                    testAlarm.activeDays[i] = dayCheckBoxes[i].isChecked();
                }
            } else {
                Arrays.fill(testAlarm.activeDays, false);
            }
            
            // 调度测试闹钟
            saveOrScheduleAlarm(testAlarm);
            Toast.makeText(MainActivity.this, "测试闹钟已设置，10秒后触发", Toast.LENGTH_SHORT).show();
        });
        
        // 保存按钮
        dialogView.findViewById(R.id.btn_save).setOnClickListener(v -> {
            // 验证时间输入
            String hourStr = etHour.getText().toString();
            String minuteStr = etMinute.getText().toString();
            
            if (hourStr.isEmpty() || minuteStr.isEmpty()) {
                Toast.makeText(MainActivity.this, "请设置时间", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新闹钟数据
            int hour = Integer.parseInt(hourStr);
            int minute = Integer.parseInt(minuteStr);
            alarm.time.set(Calendar.HOUR_OF_DAY, hour);
            alarm.time.set(Calendar.MINUTE, minute);
            alarm.time.set(Calendar.SECOND, 0);
            
            alarm.ttsText = etTts.getText().toString();
            
            // 设置星期
            boolean isRepeat = rgRepeat.getCheckedRadioButtonId() == R.id.rb_repeat;
            if (isRepeat) {
                for (int i = 0; i < dayCheckBoxes.length; i++) {
                    alarm.activeDays[i] = dayCheckBoxes[i].isChecked();
                }
            } else {
                Arrays.fill(alarm.activeDays, false);
            }
            
            // 如果是新闹钟，添加到列表
            if (alarm.id == 0) {
                alarm.id = System.currentTimeMillis();
                alarms.add(alarm);
            }
            
            // 更新列表
            Collections.sort(alarms, (a1, a2) -> a1.time.compareTo(a2.time));
            adapter.notifyDataSetChanged();
            
            // 保存到数据库或调度闹钟
            saveOrScheduleAlarm(alarm);
            Toast.makeText(MainActivity.this, "闹钟已保存", Toast.LENGTH_SHORT).show();
            
            dialog.dismiss();
        });
        
        // 取消按钮
        dialogView.findViewById(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
        
        dialog.show();
    }
    
    private void saveOrScheduleAlarm(Alarm alarm) {
        Intent intent = new Intent(this, AlarmService.class);
        intent.setAction("SCHEDULE_ALARM");
        intent.putExtra("alarm", alarm);
        startService(intent);
    }
    
    private class AlarmAdapter extends ArrayAdapter<Alarm> {
        public AlarmAdapter(MainActivity context, ArrayList<Alarm> alarms) {
            super(context, 0, alarms);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Alarm alarm = getItem(position);
            
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.alarm_item, parent, false);
            }
            
            TextView tvTime = convertView.findViewById(R.id.tv_time);
            TextView tvDays = convertView.findViewById(R.id.tv_days);
            TextView tvTts = convertView.findViewById(R.id.tv_tts);
            
            if (alarm != null) {
                tvTime.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(alarm.time.getTime()));
                
                String[] days = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < alarm.activeDays.length; i++) {
                    if (alarm.activeDays[i]) {
                        if (sb.length() > 0) sb.append(",");
                        sb.append(days[i]);
                    }
                }
                tvDays.setText(sb.toString());
                tvTts.setText(alarm.ttsText);
            }
            
            return convertView;
        }
    }
}
"""

    # 3. 更新AlarmService.java (修复闹钟触发问题)
    alarm_service = """
package com.example.voicealarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.util.Calendar;

public class AlarmService extends Service {
    private static final String TAG = "AlarmService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && "SCHEDULE_ALARM".equals(intent.getAction())) {
            Alarm alarm = intent.getParcelableExtra("alarm");
            if (alarm != null) {
                Log.d(TAG, "Scheduling alarm: " + alarm.ttsText);
                scheduleAlarm(alarm);
            }
        }
        return START_STICKY;
    }

    private void scheduleAlarm(Alarm alarm) {
        // 如果是一次性闹钟
        if (!isRepeating(alarm)) {
            scheduleSingleAlarm(alarm);
            return;
        }
        
        // 如果是重复闹钟，为每个选中的星期调度
        for (int i = 0; i < alarm.activeDays.length; i++) {
            if (alarm.activeDays[i]) {
                scheduleWeeklyAlarm(alarm, i);
            }
        }
    }
    
    private boolean isRepeating(Alarm alarm) {
        for (boolean day : alarm.activeDays) {
            if (day) return true;
        }
        return false;
    }
    
    private void scheduleSingleAlarm(Alarm alarm) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarm.time.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, alarm.time.get(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, 0);
        
        // 如果时间已过，设置到明天
        if (calendar.before(Calendar.getInstance())) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        setAlarm(calendar, alarm);
    }
    
    private void scheduleWeeklyAlarm(Alarm alarm, int dayOfWeek) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarm.time.get(Calendar.HOUR_OF_DAY));
        calendar.set(Calendar.MINUTE, alarm.time.get(Calendar.MINUTE));
        calendar.set(Calendar.SECOND, 0);
        
        // 设置到下一个选中的星期几 (Calendar.DAY_OF_WEEK从周日=1开始)
        int currentDay = calendar.get(Calendar.DAY_OF_WEEK);
        int targetDay = dayOfWeek + 1; // 转换为Calendar的星期表示
        
        // 计算天数差
        int daysUntilNext = (targetDay - currentDay + 7) % 7;
        if (daysUntilNext == 0) {
            // 如果是同一天，检查时间是否已过
            if (calendar.before(Calendar.getInstance())) {
                daysUntilNext = 7;
            }
        }
        
        calendar.add(Calendar.DAY_OF_MONTH, daysUntilNext);
        
        setAlarm(calendar, alarm);
    }
    
    private void setAlarm(Calendar calendar, Alarm alarm) {
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("alarm", alarm);
        
        // 使用唯一ID确保每个闹钟独立
        int requestCode = (int) (alarm.id + calendar.get(Calendar.DAY_OF_WEEK));
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        if (alarmManager != null) {
            Log.d(TAG, "Setting alarm at " + calendar.getTime() + " with text: " + alarm.ttsText);
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(
                    AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            } else {
                alarmManager.setExact(
                    AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            }
        }
    }
}
"""

    # 4. 更新AlarmReceiver.java (修复闪退问题)
    alarm_receiver = """
package com.example.voicealarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "AlarmReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Alarm alarm = intent.getParcelableExtra("alarm");
        if (alarm != null) {
            Log.d(TAG, "Alarm triggered: " + alarm.ttsText);
            
            // 启动闹钟界面
            Intent ringIntent = new Intent(context, RingActivity.class);
            ringIntent.putExtra("alarm", alarm);
            ringIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            
            try {
                context.startActivity(ringIntent);
            } catch (Exception e) {
                Log.e(TAG, "Failed to start RingActivity", e);
            }
        }
    }
}
"""

    # 文件列表
    files = {
        "app/src/main/res/layout/dialog_edit_alarm.xml": dialog_layout,
        "app/src/main/java/com/example/voicealarm/MainActivity.java": main_activity,
        "app/src/main/java/com/example/voicealarm/AlarmService.java": alarm_service,
        "app/src/main/java/com/example/voicealarm/AlarmReceiver.java": alarm_receiver
    }

    # 创建/替换文件
    for file_path, content in files.items():
        full_path = os.path.join(base_dir, file_path)
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        
        with open(full_path, "w", encoding="utf-8") as f:
            f.write(textwrap.dedent(content).strip())
        
        print(f"Created/Replaced: {file_path}")

def main():
    project_dir = input("请输入项目根目录路径（包含app文件夹的目录）: ").strip()
    if not os.path.isdir(project_dir):
        print("错误：指定的目录不存在")
        return
    
    replace_files(project_dir)
    print("""
    闹钟功能已更新，主要修改包括：
    1. 修复闹钟保存问题
    2. 修复闹钟触发闪退问题
    3. 时间设置改为直接编辑输入
    4. 添加测试按钮可立即测试闹钟
    5. 添加详细日志便于调试
    """)

if __name__ == "__main__":
    main()
